// miniprogram/pages/index/index.js
const db = wx.cloud.database()
const imgScroll = db.collection('imgScroll')
const userInfo = db.collection('userInfo')

Page({
  /**
   * 页面的初始数据
   */
  data: {
    // 当前风景所有笔记
    scrollItemData: [],
    scrollItemImgData1: [],
    scrollItemImgData2: [],
    // 当前想要发布的笔记内容
    currentNote: "",
    // 当前风景索引
    currentView: "eb327c1463293cbd0031e1d04257f6eb",
    // 用户位置信息
    locationInfo: {},
    avatarUrl: undefined,
    nickName: undefined,
    signature: undefined,
    latitude: undefined,
    longitude: undefined,
  },
  // 格式化时间
  getFormatDateTime: function () {
    var date = new Date();
    var year = date.getFullYear();
    var month = (date.getMonth() + 1) < 10 ? "0" + (date.getMonth() + 1) : (date.getMonth() + 1);
    var day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    var hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours();
    var minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes();
    var second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
    return [year, '/', month, '/', day, ' ', hour, ':', minute, ':', second].join('');
  },
  // 选择当前风景
  onCurrentView: function (event) {
    const index = event.currentTarget.dataset.index
    // 更改首页笔记
    imgScroll.where({ _id: index }).get().then(res => {
      const note = res.data[0].note ?? []
      this.setData({
        currentView: index,
        scrollItemData: note
      })
    })
  },
  // 改变发表笔记内容函数
  onChangeNoteContent: function (res) {
    const val = res.detail.value
    this.setData({
      currentNote: val
    })
  },
  // 发送笔记函数
  toSendNote: function () {
    const content = this.data.currentNote
    const { currentView, signature, nickName, avatarUrl, latitude, longitude } = this.data
    let url
    if (content) {
      imgScroll.where({ _id: currentView }).get().then(res => {
        url = res.data[0].url
        if (!res.data[0].note) {
          imgScroll.where({ _id: currentView }).update({
            data: { note: [{ id: 0, signature, nickName, avatarUrl, latitude, longitude, content, url, time: this.getFormatDateTime() }] }
          })
        } else {
          res.data[0].note.unshift({
            id: res.data[0].note.length, signature, nickName, avatarUrl, latitude, longitude, content, url, time: this.getFormatDateTime()
          })
          imgScroll.where({ _id: currentView }).update({ data: { note: res.data[0].note } })
        }
        userInfo.where({ nickName, avatarUrl }).get().then(res => {
          res.data[0].myAllNote.unshift({ signature, nickName, avatarUrl, latitude, longitude, content, url, time: this.getFormatDateTime() })
          userInfo.where({ nickName: nickName, avatarUrl: avatarUrl }).update({ data: { myAllNote: res.data[0].myAllNote } })
        })
        this.setData({
          scrollItemData: res.data[0].note
        })
      })
      this.setData({
        currentNote: ""
      })
    }
  },
  // 点赞
  onStar: function (event) {
    let id = event.currentTarget.dataset.id
    this.data.scrollItemData.map((item, key) => {
      if (item.id === id) {
        let star = `scrollItemData[${key}].star`
        this.setData({
          [star]: !this.data.scrollItemData[key].star
        })
      }
    })
  },
  // 去到评论页
  ToComment: function (e) {
    const { currentview, data } = e.currentTarget.dataset
    wx.navigateTo({
      url: '/pages/comment/comment',
    })
    wx.setStorage({
      key: "commentInfo",
      data: { currentview: currentview, ...data }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const currentView = this.data.currentView
    // 从云数据库获取图片数据
    imgScroll.get().then((res) => {
      const { data } = res
      this.setData({
        scrollItemImgData1: data.slice(0, 10),
        scrollItemImgData2: data.slice(10)
      })
    })
    // 初始加载更新封面的笔记
    imgScroll.doc(currentView).get().then(res => {
      const data = res.data.note
      this.setData({
        scrollItemData: data
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // 查看用户是否登录
    wx.getStorage({
      key: "userInfo",
      success: (res) => {
        wx.getStorage({
          key: 'userInfo',
          success: (res) => {
            const { signature, nickName, avatarUrl } = res.data
            this.setData({ signature, nickName, avatarUrl })
          }
        })
        wx.getStorage({
          key: 'locationInfo',
          success: (res) => {
            const { latitude, longitude } = res.data
            this.setData({ latitude, longitude })
          }
        })
      },
      fail: (err) => {
        if (err) { wx.switchTab({ url: '/pages/my/my' }) }
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    const { currentView } = this.data
    // 初始加载更新封面的笔记
    imgScroll.doc(currentView).get().then(res => {
      const data = res.data.note
      this.setData({
        scrollItemData: data
      })
    }).then(() => {
      wx.stopPullDownRefresh()
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})